export default{
  namespaced:true,
  state:() =>({
    //购物車数组，存儲商品信息对象
    shopCar:JSON.parse(uni.getStorageSync('saveShopCar')||'[]')
  }),
  //state里的數據只能被mutations調用
  mutations:{
    addToShopCar(state, product){
      const findResult = state.shopCar.find(x => x.product_id === product.product_id)
      console.log(findResult)
      //如果購物車已有該產品,就在該產品數量上加一，如沒有就新增進去
      if(!findResult){
        state.shopCar.push(product)
      }else{
        findResult.product_count++
      }
      this.commit('shopCar/saveToStorage')
    },
    //保存購物車數據到本地
    saveToStorage(state){
      uni.setStorageSync('saveShopCar',JSON.stringify(state.shopCar))
    },
    //更新購物車商品狀態
    updateProductState(state, product){
      const findResult = state.shopCar.find(x => x.product_id === product.product_id)
      if(findResult){
        findResult.product_state = product.product_state
      }
      this.commit('shopCar/saveToStorage')
    },
    //更新數量
    updateProductCount(state, product){
      const findResult = state.shopCar.find(x => x.product_id === product.product_id)
      if(findResult){
        findResult.product_count = product.product_count
      }
      this.commit('shopCar/saveToStorage')
    },
    //以ID刪除对应商品
    removeProductByID(state, product){
      //用filter过濾器过濾出來不等于对应ID的商品，那它就被清掉了
      state.shopCar = state.shopCar.filter(x => x.product_id !== product.product_id)
      this.commit('shopCar/saveToStorage')
    },
    //全选或全反选
    stateAllChanged(state, newState){
      state.shopCar.forEach(x => x.product_state = newState)
      this.commit('shopCar/saveToStorage')
    }
  },
  
  getters:{
    //所有商品總數
    total(state){
      let c = 0
      state.shopCar.forEach(x => c += x.product_count)
      return c
    },
    //已勾选商品數量
    checkedCount(state){
      return state.shopCar.filter(x => x.product_state).reduce((total, product) => {return total += product.product_count}, 0)
    },
    //計算已勾选商品的總价格
    checkedTotalPrice(state){

      return state.shopCar.filter(x => x.product_state).reduce((total, product) => {return total += product.product_count * parseFloat(product.price)},0).toFixed(2)
    }
  }
}